﻿#include <QPushButton>
#include <QMessageBox>
#include <QIcon>

#include "mainwindow.h"
#pragma execution_character_set("utf-8")

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QIcon icon(":/btnIcon/qtuber.png");
    systemTray = new QSystemTrayIcon(this);
    systemTray->setIcon(icon);
    systemTray->setToolTip("Your Qtuber");
    minimumAct = new QAction("最小化窗口", this);
    //Note the differences between hide() and showMinimized().
    connect(minimumAct, SIGNAL(triggered()), this, SLOT(hide()));
    maximumAct = new QAction("最大化窗口", this);
    connect(maximumAct, SIGNAL(triggered()), this, SLOT(showMaximized()));
    restoreAct = new QAction("还原窗口", this);
    connect(restoreAct, SIGNAL(triggered()), this, SLOT(showNormal()));
    quitAct = new QAction("退出应用", this);
    connect(quitAct, SIGNAL(triggered()), qApp, SLOT(quit()));
    pContextMenu = new QMenu(this);
    pContextMenu->addAction(minimumAct);
    pContextMenu->addAction(maximumAct);
    pContextMenu->addAction(restoreAct);
    pContextMenu->addSeparator();
    pContextMenu->addAction(quitAct);
    systemTray->setContextMenu(pContextMenu);
    systemTray->show();

    QMovie *movie = new QMovie(":/btnIcon/welcome.gif");
    ui->title->setMovie(movie);
    movie->start();
    ui->title->show();

    setWindowTitle("Qtuber");
    setWindowIcon(QIcon(":/btnIcon/qtuber.png"));
    connect(ui->login, SIGNAL(clicked()), this, SLOT(signIn()));
    connect(ui->reg, SIGNAL(clicked()), this, SLOT(toSignUp()));
    connect(TRANS->getSignalGun(), SIGNAL(reSignIn(InfoHead*, QJsonDocument, QHostAddress, quint16)), this, SLOT(reSignIn(InfoHead*, QJsonDocument, QHostAddress, quint16)));
}

void MainWindow::signIn() {
    QJsonDocument doc;
    QJsonObject obj;
    obj.insert("account", ui->account->text());
    obj.insert("password", ui->password->text());
    doc.setObject(obj);
    QByteArray bytes = doc.toJson();
    qint64 fileSize = bytes.size();

    InfoHead *infoHead = new InfoHead(fileSize, 0, Operation::SignIn, Operation::Success,
                                      0, 0, QString(""));
    TRANS->writeUdp(infoHead, bytes, CONF.serverIp, CONF.udpPort);
}

void MainWindow::reSignIn(InfoHead *infoHead, QJsonDocument doc, QHostAddress ip, quint16 port) {
    if (infoHead->getStateCode() == Operation::Success) {
        TalkMainWindow * talk = new TalkMainWindow();
        Config::getInstance()->setUserId(doc.object()["id"].toInt());
        qDebug() << "doc :::" << doc;
        talk->getSolochat()->initRecentContactList(doc);
        talk->getGroupchat()->initGroupRecentContactList(doc);
        this->hide();
        talk->show();
    }
    else {
        QMessageBox *pmsg = new QMessageBox(QMessageBox::Critical,"登陆失败","账号密码错误",QMessageBox::Ok,this);
        pmsg->exec();
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::toSignUp() {
    SignUpWidget reg;
    reg.exec();
}



